import { getList } from '@/api/api-manage/list'
import { commonExportListToExcel } from '@/api/common'
import { usePagination } from '@/hooks/usePagination'
import useTableRowSelection from '@/hooks/useTableRowSelection'
import useDictStore from '@/store/modules/dict'
import { formatDate, omitEmptyValue } from '@/utils/common'
import type { FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'

export default function useList() {
  const loading = ref(false)
  const queryParams = reactive({
    apiName: '',
    checkStatus: null,
    isMine: 'true',
  })
  const { api_type } = useDictStore().getDicts('api_type')
  const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
  const formRef = ref<FormInstance>()
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
    },
    {
      label: '接口ID',
      prop: 'id',
      minWidth: 100,
    },
    {
      label: '接口服务名称',
      prop: 'apiName',
      minWidth: 150,
    },
    {
      label: '接口路径',
      prop: 'requestPath',
      minWidth: 150,
    },
    {
      label: '接口类型',
      prop: 'apiType',
      minWidth: 100,
      formatter: ({ apiType }) => api_type.getLabel(apiType),
    },
    {
      label: '接口发布时间',
      prop: 'publishTime',
      minWidth: 180,
      formatter: ({ publishTime }) => formatDate(publishTime),
    },
    {
      label: '最后修改',
      prop: 'updateTime',
      minWidth: 180,
      formatter: ({ updateTime }) => formatDate(updateTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]
  const dataList = ref([])

  /** 查询列表 */
  async function onSearch() {
    loading.value = true
    const { rows, total } = await getList(
      omitEmptyValue({
        apiName: queryParams.apiName,
        sortBy: 1,
        isMine: queryParams.isMine,
        orderByColumn: 'update_time',
        isAsc: 'desc',
        ...paginationParams.value,
      })
    ).finally(() => (loading.value = false))
    dataList.value = rows
    pagination.total = total
  }

  /** 重置新增的表单  */
  async function resetForm() {
    formRef.value.resetFields()
    queryParams.apiName = ''
    await onSearch()
  }
  const { selectedRows, onRowSelectionChange } = useTableRowSelection()

  /** 导出按钮操作 */
  function onExport() {
    const params = {
      ...queryParams,
      ids: selectedRows.value.map((item) => item.id),
    }
    commonExportListToExcel('/manage/apiInfo/export', params)
  }

  return {
    isLoading: loading,
    pagination,
    formRef,
    columns,
    queryParams,
    dataList,
    resetForm,
    changePageNumber,
    changePageSize,
    onSearch,
    onExport,
    onRowSelectionChange,
  }
}
